const path = require('path');
const glob = require('glob');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackTagsPlugin = require('html-webpack-tags-plugin');
const merge = require('webpack-merge');
const devConfig = require('./dev');
const fs = require('fs');
const { paths } = require('../utils');
const { webpackConfig, webpackDevServerHotConfig } = require('./lib/config');
const feHost = webpackConfig.devServer.feHost;
const host = webpackConfig.devServer.host;
const port = webpackConfig.devServer.port;
const serverHost = '0.0.0.0';
const mock = require(path.join(paths.roots, 'src/mock'));

let hosts = fs.readFileSync('/private/etc/hosts', 'utf-8');
if (hosts.indexOf(feHost) === -1) {
  console.log('***************************************************\n');
  console.log('请在hosts里添加\n');
  console.log(`${serverHost} ${feHost}\n`);
  console.log('***************************************************\n');
  process.exit();
}

const htmlArr = glob.sync(path.join(paths.srcPath, 'pages/*/index.js'))

const htmlPluginArr = htmlArr.map(v => {
  const pageName = v.replace(new RegExp(`${paths.srcPath}/(.+)/index.js`), '$1');
  const page = webpackConfig.pages && webpackConfig.pages.find(v => v.path === pageName) || {};
  let filename = pageName;
  if(typeof page.url === 'string'){
    filename = page.url.replace(/^\//, '') || 'index.html'
  }
  return new HtmlWebpackPlugin({
    inject: true,
    rootId: page.rootId || 'root',
    title: page.title || `${pageName} 页面`,
    favicon: path.join(paths.srcPath, '/static/images/favicon.ico'),
    chunks: [pageName],
    template: path.join(__dirname, '../template/index.html'),
    filename: filename,
  })
})

module.exports = (env, argv) => {
  process.env.mode = 'serverHot';
  let pageUrl = process.env.pageUrl || '';
  if(pageUrl){
    pageUrl = /^\//.test(pageUrl) ? pageUrl : `/${pageUrl}`;
  }

  if (webpackDevServerHotConfig) {
    return merge(devConfig(env, argv), webpackDevServerHotConfig);
  }
  return merge(devConfig(env, argv), {
    output: {
      publicPath: '/',
    },
    resolve: {
      alias: {
        'react-dom': '@hot-loader/react-dom'
      }
    },
    devServer: {
      historyApiFallback: {
        rewrites: [
          {
            from: /\.json$/,
            to: ''
          },
          {
            from: /.*/g,
            to: '/'
          }
        ]
      },
      headers: { 'Access-Control-Allow-Origin': '*' },
      public: `${feHost}:${port}${pageUrl}`,
      disableHostCheck: true,
      clientLogLevel: 'none',
      host: serverHost,
      open: webpackConfig.devServer.defaultBrowser,
      stats: 'none',
      overlay: false,
      port,
      quiet: true,
      proxy: {
        '/mock': {
          target: `http://${serverHost}:${port}`,
          changeOrigin: true,
          pathRewrite: { '^/mock': '' },
          secure: false
        },
        '**/*.json': {
          target: `http://${host}`,
          changeOrigin: true,
          secure: false,
        },
        ...webpackConfig.devServer.proxy
      },
      before(app, server) {
        mock && mock(app, server);
      }
    },
    plugins: [
      ...htmlPluginArr,
      new HtmlWebpackTagsPlugin({
        tags: [
          ...Object.keys(webpackConfig.dll).map(v => `static/js/common/${v}.js`),
          'js/common/common.js',
          'css/common/common.css'
        ],
        append: false
      })
    ]
  });
}